from waveapi import events
from waveapi import model
from waveapi import robot
from waveapi import robot_abstract
from waveapi import document


import logging


def OnParticipantsChanged(properties, context):
    """Invoked when any participants have been added/removed."""
    added = properties['participantsAdded']
    for p in added:
        Notify(context)

def OnRobotAdded(properties, context):
    """Invoked when the robot has been added."""
    root_wavelet = context.GetRootWavelet()
    root_wavelet.CreateBlip().GetDocument().SetText("Type /createWave to create a new wave with all current participants as participants")

def OnBlipSubmitted(properties, context):
    """Invoked when a new blip has ben added to the wave."""
    doc = context.GetBlipById(properties['blipId']).GetDocument()
    text = doc.GetText()
    if text.find('/createWave') == 0:
        _newWave       = robot_abstract.NewWave(context, context.GetRootWavelet().GetParticipants())
        _newWave.SetTitle("New Wave's, created through Robbie Waverson")
        _newRootBlipId = _newWave.GetRootBlipId()
        _newRootBlip   = context.GetBlipById(_newRootBlipId)
        _newDocument   = _newRootBlip.GetDocument()
        _newDocument.AppendText("Hi!")



def Notify(context):
    root_wavelet = context.GetRootWavelet()
    root_wavelet.CreateBlip().GetDocument().SetText("Hi everybody!")

def main():
    myRobot = robot.Robot('Robbie Waverson', 
        image_url='http://robbiewaverson.appspot.com/static/icon_devil.png',
        version='0.1.0.11',
        profile_url='http://robbiewaverson.appspot.com/')
    #myRobot.RegisterHandler(events.WAVELET_PARTICIPANTS_CHANGED, OnParticipantsChanged)
    myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded)
    myRobot.RegisterHandler(events.WAVELET_BLIP_CREATED, OnBlipSubmitted)
    myRobot.RegisterHandler(events.BLIP_SUBMITTED, OnBlipSubmitted)
    myRobot.Run()


if __name__ == '__main__':
    main()
